package org.skywind.WindSearch.servlet;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.omg.CORBA.Context;
import org.skywind.WindSearch.dao.SearchAction;
import org.skywind.WindSearch.util.Guest;
import org.skywind.tools.Log;

/**
 * 执行搜索任务的Servlet，即搜索引擎用户接口
 * 
 * @author Administrator
 * 
 */
public class Search extends HttpServlet {
	private ServletContext app;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		this.app = config.getServletContext();
		super.init(config);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		SearchAction sa = (SearchAction)app.getAttribute("dbaction");
		Guest guest = (Guest) req.getSession().getAttribute("guest");
		long starttime = System.currentTimeMillis();
		int page = 1; 
		int pageSize = guest.getPageSize();
		String key = "";
		String type = (String) req.getSession().getAttribute("t");
		String meta = req.getParameter("meta");
		try {
			key = req.getParameter("q");
			key = new String(key.getBytes("ISO-8859-1"), "utf-8");
			page = Integer.parseInt(req.getParameter("page"));
			pageSize = Integer.parseInt(req.getParameter("pageSize"));
			if (!type.equalsIgnoreCase(guest.getType()))
				throw new Exception();
		} catch (Exception e) {
			if (key != null && type != null && !key.equals("")) {
				try{
				  
				boolean suc = guest.doSearch(type, key, meta);//执行搜索任务
				long endtime = System.currentTimeMillis();
				guest.getResult().setTime(endtime - starttime);
				if (suc) {
					sa.insertKey(key, req.getRemoteAddr());
				} else {
					Log.println("[Search]Lost!" + guest);
				}
				if (page > guest.getPageCount()) {
					page = guest.getPageCount();
				}
				}catch(Exception es){
					es.printStackTrace();
				}
			}
		}

		guest.setCurrPage(page);
		guest.setPageSize(pageSize);

		String tc = guest.getType();
		RequestDispatcher rd = null;
		if (key==null||key.equals("")||tc == null || tc.length() == 0) {
			resp.sendRedirect("");
			return;
		} else {
			rd = req.getRequestDispatcher("/search.jsp");
		}
		rd.forward(req, resp);

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}

}
